package com.qq.util;

import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Verify {
	private static Verify verify = new Verify();
	private Verify(){}
	public static Verify getInstance(){
		return verify;
	}
	public boolean  VerifyOpenID(String openid, String timestamp, String oauth_signature,String appkey){
	    String str = openid+timestamp;
	    String signature = getSignature(str, appkey);
	    return signature.equals(QHttpUtil.formParamDecode(oauth_signature));	
	}
	
	public String getSignature(String str, String appkey)
	{
		String signature = "";
	    try {
			signature = calculateRFC2104HMAC(str, appkey);
		} catch (SignatureException e) {
			e.printStackTrace();
		}
	    return signature;
	}

	/**
	* Computes RFC 2104-compliant HMAC signature.
	* * @param data
	* The data to be signed.
	* @param key
	* The signing key.
	* @return
	* The Base64-encoded RFC 2104-compliant HMAC signature.
	* @throws
	* java.security.SignatureException when signature generation fails
	*/
	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
	public String calculateRFC2104HMAC(String data, String key) throws SignatureException{
	String result;
	try {

		// get an hmac_sha1 key from the raw key bytes
		SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
	
		// get an hmac_sha1 Mac instance and initialize with the signing key
		Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
		mac.init(signingKey);
	
		// compute the hmac on input data bytes
		byte[] rawHmac = mac.doFinal(data.getBytes());
	
		// base64-encode the hmac
		result = Base64Encoder.encode(rawHmac);

	} catch (Exception e) {
		throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
	}
	return result;
	}

}
